package com.smart.translator.ui.voice;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.smart.translator.databinding.FragmentVoiceBinding;
import com.smart.translator.data.model.Language;
import java.util.List;

public class VoiceFragment extends Fragment {
    private FragmentVoiceBinding binding;
    private VoiceViewModel viewModel;
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentVoiceBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this).get(VoiceViewModel.class);
        checkAndRequestPermissions();
        setupViews();
        observeViewModel();
    }

    private void checkAndRequestPermissions() {
        String[] permissions = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE
        };
        
        for (String permission : permissions) {
            if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                getActivity().requestPermissions(permissions, PERMISSION_REQUEST_CODE);
                return;
            }
        }
    }

    private void setupViews() {
        List<Language> languages = viewModel.getLanguages();
        ArrayAdapter<Language> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, languages);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.sourceLanguageSpinner.setAdapter(adapter);
        binding.targetLanguageSpinner.setAdapter(adapter);

        binding.sourceLanguageSpinner.setSelection(viewModel.getSourceLangIndex().getValue() != null ? viewModel.getSourceLangIndex().getValue() : 0);
        binding.targetLanguageSpinner.setSelection(viewModel.getTargetLangIndex().getValue() != null ? viewModel.getTargetLangIndex().getValue() : 1);

        binding.sourceLanguageSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                viewModel.setSourceLangIndex(position);
            }
            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });
        binding.targetLanguageSpinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                viewModel.setTargetLangIndex(position);
            }
            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });
        binding.swapButton.setOnClickListener(v -> viewModel.switchLanguages());
        binding.recordButton.setOnClickListener(v -> {
            Boolean isRec = viewModel.getIsRecording().getValue();
            if (isRec != null && isRec) {
                viewModel.stopRecording();
                binding.recordButton.setText("开始录音");
            } else {
                viewModel.startRecording();
                binding.recordButton.setText("停止录音");
            }
        });
        binding.playButton.setOnClickListener(v -> viewModel.playTranslation());
        binding.copyButton.setOnClickListener(v -> viewModel.copyTranslation());
    }

    private void observeViewModel() {
        viewModel.getVoiceText().observe(getViewLifecycleOwner(), text -> binding.voiceText.setText(text));
        viewModel.getTranslatedText().observe(getViewLifecycleOwner(), text -> binding.translatedText.setText(text));
        viewModel.getIsRecording().observe(getViewLifecycleOwner(), isRec -> {
            if (isRec != null && isRec) {
                binding.recordButton.setText("停止录音");
            } else {
                binding.recordButton.setText("开始录音");
            }
        });
        viewModel.getIsLoading().observe(getViewLifecycleOwner(), isLoading -> binding.progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE));
        viewModel.getError().observe(getViewLifecycleOwner(), error -> {
            if (error != null && !error.isEmpty()) {
                Toast.makeText(requireContext(), error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
} 